﻿using MediatR;
using PublicCommon;
using T_settlement.Domain;
using T_settlement.Infrastructure.Interfacec;
using T_settlement.Read.API.Application.Command.PaymentCommand;

namespace T_settlement.Read.API.Application.CommandHandlers.PaymentCommandHandlers
{
    public class GetPaymentCommandHandlers:IRequestHandler<GetPaymentCommand,PageResult<Payment>>
    {
        private readonly IPaymentRepository paymentRepository;

        public GetPaymentCommandHandlers(IPaymentRepository paymentRepository)
        {
            this.paymentRepository = paymentRepository;
        }

        public async Task<PageResult<Payment>> Handle(GetPaymentCommand request, CancellationToken cancellationToken)
        {
            var list = paymentRepository.GetAllAsync().Result.Where(x => x.IsDel == false).AsQueryable();

            if (!string.IsNullOrEmpty(request.Title))
            {
                list = list.Where(x => x.Title.Contains(request.Title));
            }

            if (!string.IsNullOrEmpty(request.Approver))
            {
                list = list.Where(x => x.Title.Contains(request.Approver));
            }

            if (request.AuditState!= 0 && request.AuditState != null)
            {
                list = list.Where(x => x.AuditState == request.AuditState);
            }

            if (!string.IsNullOrEmpty(Convert.ToString(request.PaymentTime)))
            {
                list = list.Where(x => x.PaymentTime == request.PaymentTime);
            }

            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling((totalCount * 1.0) / request.pageSize);
            var res =  list.OrderByDescending(x=>x.PaymentId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return new PageResult<Payment>
            {
                PageCount = pageCount,
                TotalCount = totalCount,
                List = res
            };
        }
    }
}
